package com.kaiwukj.android.ufamily.mvp.ui.page.mine.evaluate;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.SizeUtils;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseMvpFragment;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.di.component.DaggerOrderComponent;
import com.kaiwukj.android.ufamily.di.module.OrderModule;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.OrderEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.OrderEvaluateResult;
import com.kaiwukj.android.ufamily.mvp.ui.page.order.OrderContract;
import com.kaiwukj.android.ufamily.mvp.ui.widget.SpaceItemDecoration;
import com.kaiwukj.android.ufamily.utils.FormatUtils;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import butterknife.BindView;

public class OrderEvaluateFragment extends BaseMvpFragment<EvaluatePresenter> implements OrderContract.EvaluateView {

    private static final int REQUEST_EVALUATE = 101;

    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.empty_view)
    QMUIEmptyView emptyView;


    private OrderEvaluateAdapter mEvaluateAdapter;

    private int type = 0;
    private int page = 1;
    private int pageSize = 12;
    private boolean isLoadingMore = false;

    private int eventPos = -1;//操作的item position


    public static OrderEvaluateFragment newInstance(int type) {
        OrderEvaluateFragment fragment = new OrderEvaluateFragment();
        fragment.type = type;
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        super.setupFragmentComponent(appComponent);
        DaggerOrderComponent.builder()
                .appComponent(appComponent)
                .orderModule(new OrderModule(this))
                .build().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.widget_list_normal;
    }

    @Override
    protected void initView() {
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isLoadingMore = true;
                ++page;
                loadData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                loadData();
            }
        });
        rvList.setPadding(0, SizeUtils.dp2px(10), 0, 0);
        rvList.setLayoutManager(new LinearLayoutManager(getContext()));
        rvList.addItemDecoration(new SpaceItemDecoration(10));
        mEvaluateAdapter = new OrderEvaluateAdapter(type);
        rvList.setAdapter(mEvaluateAdapter);
        // mEvaluateAdapter.setEmptyView(R.layout.empty_view_common_container);
        mEvaluateAdapter.setOnItemClickListener((adapter, view, position) -> {
            ARouter.getInstance().build(ARouterUrlKt.OrderDetailUrl)
                    .withInt("orderId", (int) adapter.getItemId(position))
                    .navigation();
        });
        mEvaluateAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            OrderEvaluateResult item = mEvaluateAdapter.getItem(position);
            if (view.getId() == R.id.btn_rating) {
                eventPos = position;
                ARouter.getInstance().build(ARouterUrlKt.OrderEvaluateEditUrl)
                        .withInt("orderId", item.getId())
                        .withString("avatarUrl", item.getThumbnail())
                        .withString("serviceName", item.getServiceParameterName())
                        .withString("servicePrice", FormatUtils.formatPrice(item.getActualprice()))
                        .navigation(getActivity(), REQUEST_EVALUATE);
            }
        });
    }

    @Override
    protected void initData(Bundle savedInstanceState) {

    }


    @Override
    protected void initDataSupport() {
        super.initDataSupport();
        emptyView.show(true);
        loadData();
    }

    private void loadData() {
        if (type == 0) {
            mPresenter.fetchNotEvaluate(page, pageSize);
        } else {
            mPresenter.fetchEvaluate(page, pageSize);
        }
    }

    @Override
    public void onFetchResult(List<OrderEvaluateResult> results) {
        emptyView.hide();
        if (isLoadingMore) {
            isLoadingMore = false;
            mEvaluateAdapter.addData(results);
            if (results.size() < pageSize) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadMore();
            }
        } else {
            mEvaluateAdapter.setList(results);
            refreshLayout.finishRefresh(true);
        }
        checkDataIsEmpty();
    }

    private void checkDataIsEmpty() {
        if (mEvaluateAdapter == null || mEvaluateAdapter.getItemCount() == 0) {
            emptyView.show("暂没有数据!", "");
        }
    }

    @Override
    public void onTaskErr(int taskId) {
        super.onTaskErr(taskId);
        emptyView.hide();
        refreshLayout.finishRefresh(false);
        refreshLayout.finishLoadMore(false);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_EVALUATE) {
            if (resultCode == RESULT_OK) {
                mEvaluateAdapter.removeAt(eventPos);
                checkDataIsEmpty();
            }
        }
    }

    @Subscribe
    public void onOrderEvent(OrderEvent event) {
        if (event.getEventCode() == OrderEvent.DELETE) {
            mEvaluateAdapter.removeItemById(event.getEventId());
        }
    }
}
